import cloud from '@lafjs/cloud'
let dbName = "admin-class-student"
const db = cloud.mongo.db


export default async function (ctx: FunctionContext) {
  let data = ctx.body
  let whereJson = {}  //班级查询条件
  let findObj = {}  //班级学员查询条件  
  if (data.curriculum_id && data.curriculum_id.length) {
    whereJson["curriculumId"] = { $in: data.curriculum_id }
  }
  if (data.year) {
    whereJson["classOpeningTime"] = { $regex: data.year.toString(), $options: "i" }
  }

  if (!cloud.utils.isEmptyObject(whereJson)) {
    let classList = await db.collection("admin-class").find(whereJson).project({ _id: 1 }).toArray()
    let arr = []
    if (classList && classList.length) {
      classList.forEach(element => {
        arr.push(element._id)
      });
    }
    findObj["classId"] = { $in: arr }
  }

  let aa = await db.collection(dbName).find(findObj).project({ classId: 1, isExamination: 1 }).toArray()
  let result = cloud.utils.sameSortArr(aa, "classId")
  let classAll = await db.collection("admin-class").find({}).project({ className: 1 }).toArray()
  let arr = []
  result.forEach(element => {
    let index = cloud.utils.findIndexByField(classAll, "_id", element.name)
    if (index != -1) {
      arr.push({
        classId: element.name,
        className: classAll[index].className,
        classAll: element.origin.length,
        classExamination: getTotal(element.origin)
      })
    }
  });

  function getTotal(array) {
    let news = []
    array.forEach(element => {
      if (element.isExamination && element.isExamination == 1) news.push(element)
    });
    return news.length
  }

  return cloud.utils.requestReturn({ data: arr })
}
